﻿using System;
using System.Web;
using System.Web.UI;

namespace Hanhud.Web.UI.WebControls
{
    public class DIVPager : System.Web.UI.WebControls.WebControl , System.Web.UI.IPostBackEventHandler
    {
        private int m_nTotalItemCount, m_nSelectedPage, m_nDisplayPage, m_nItemsPerPage;
        private string m_strRelativeUrl = string.Empty;
        private bool m_bAutoPostBack = true;

        /// <summary>
        /// Format parameters
        /// {0} : Selected page index
        /// </summary>
        public string RelativeUrl
        {
            set { this.m_strRelativeUrl = value; }
        }
        // True: Auto post back
        public bool AutoPostBack
        {
            set { this.m_bAutoPostBack = value; }
        }

        // Index of selected page
        public int SelectedPage
        {
            get
            {
                m_nSelectedPage = (ViewState["SelectedPage"] == null) ? 1 : (int)ViewState["SelectedPage"];
                return m_nSelectedPage;
            }
            set
            {
                ViewState["SelectedPage"] = m_nSelectedPage = value;
            }
        }
        // Number of Items
        public int TotalItemCount
        {
            get
            {
                m_nTotalItemCount = (ViewState["TotalItemCount"] == null) ? 1 : (int)ViewState["TotalItemCount"];
                return m_nTotalItemCount;
            }
            set
            {
                ViewState["TotalItemCount"] = m_nTotalItemCount = value;
            }
        }
        // Number of items per page
        public int ItemsPerPage
        {
            get
            {
                m_nItemsPerPage = (ViewState["ItemsPerPage"] == null) ? 1 : (int)ViewState["ItemsPerPage"];
                return m_nItemsPerPage;
            }
            set
            {
                ViewState["PageSize"] = m_nItemsPerPage = value;
            }
        }
        // Number of pages will be displayed
        public int DisplayPage
        {
            get
            {
                m_nDisplayPage = (ViewState["DisplayPage"] == null) ? 1 : (int)ViewState["DisplayPage"];
                return m_nDisplayPage;
            }
            set
            {
                if (value % 2 != 0)  ViewState["DisplayPage"] = m_nDisplayPage = value;
                else ViewState["DisplayPage"] = m_nDisplayPage = value + 1;
            }
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            int prevPage, nextPage, startPage, endPage, totalPage;

            totalPage = (int)Math.Floor((double)m_nTotalItemCount / m_nItemsPerPage);
            if (m_nTotalItemCount % m_nItemsPerPage != 0 || totalPage == 0) totalPage += 1;
            
            // Lay danh sach cac chi so' trang hien tai (danh sach nay phu thuoc vao chi so trang hien, tong so strang va so trang duoc hien thi)
            startPage = ((m_nSelectedPage + m_nDisplayPage - 2) <= totalPage) ? (((m_nSelectedPage - m_nDisplayPage + 2) > 0) ? (m_nSelectedPage - m_nDisplayPage + 2) : 1) : ((totalPage - m_nDisplayPage > 0) ? (totalPage - m_nDisplayPage) : 1);
            endPage = ((m_nSelectedPage + m_nDisplayPage - 2) <= totalPage) ? ((m_nSelectedPage - 2 > 0) ? (m_nSelectedPage + m_nDisplayPage - 2) : ((m_nDisplayPage > totalPage) ? totalPage : m_nDisplayPage)) : totalPage;

            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            // Hien thi trang truoc do
            if (m_nSelectedPage > 1)
            {
                prevPage = m_nSelectedPage - 1;
                RenderItem(writer, "&laquo; Lùi lại", prevPage);
            }

            // Hien thi trang dau tien
            if (m_nSelectedPage >= m_nDisplayPage)
            {
                RenderItem(writer, "1", 1);
                RenderItem(writer, "...", -1);
            }
            
            // hien thi trang
            for (int i = startPage; i <= endPage; i++)
            {
                string label = i.ToString();

                if (i == m_nSelectedPage) RenderItem(writer, label, 0);
                else RenderItem(writer, label, i);

            }

            // hien thi trang tiep theo
            if (endPage < totalPage)
            {
                nextPage = m_nSelectedPage + 1;
                RenderItem(writer, "Tiếp &raquo;", nextPage);
            }

            // hien thi trang cuoi
            RenderItem(writer, "Trang cuối", totalPage);

            writer.RenderEndTag();
        }
        protected void RenderItem(HtmlTextWriter writer, string text, int pageNum)
        {
            if (pageNum > 0)
            {
                if (string.IsNullOrEmpty(m_strRelativeUrl))
                    writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackClientHyperlink(this, pageNum.ToString()));
                else
                {
                    if(m_strRelativeUrl.IndexOf('?') > 0)
                        writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ResolveUrl(string.Format("{0}&p={1}", m_strRelativeUrl, pageNum)));
                    else writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ResolveUrl(string.Format("{0}?p={1}", m_strRelativeUrl, pageNum)));
                }

                writer.RenderBeginTag(HtmlTextWriterTag.A);
            }
            else
            {
                if(pageNum == 0)
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "selected");
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
            }

            writer.Write(text);

            //if (pageNum != 0) writer.RenderEndTag();
            writer.RenderEndTag();
        }
        public event EventHandler SelectedPageIndexChanged;
        #region IPostBackEventHandler Members

        public void RaisePostBackEvent(string eventArgument)
        {
            int newPage;

            if (int.TryParse(eventArgument, out newPage))
            {
                SelectedPage = newPage;
                OnSelectedPageIndexChanged(EventArgs.Empty);
            }
        }
        virtual public void OnSelectedPageIndexChanged(EventArgs e)
        {
            if (SelectedPageIndexChanged != null) SelectedPageIndexChanged(this, e);
        }
        #endregion
    }
}
